package com.yiyahui.project.erp.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.yiyahui.common.utils.DateUtils;
import com.yiyahui.common.utils.PinyinUtil;
import com.yiyahui.framework.redis.RedisCache;
import com.yiyahui.project.erp.service.IYiyaIDService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class YiyaIDServiceImpl implements IYiyaIDService {
    @Autowired
    private RedisCache redisCache;

    /**
     * 系统所需序列号生成 生成规则 首字母+日期（8位）+序列号（2位）
     * 
     * @param type    类型-BLH（病历号） JDH（建档号）LS(临时患者) 可直接使用IYiyaIDService.IDType_BINGLIHAO
     * @param chinese 首字母前缀汉字（比如门店，比如名字)
     * @return 根据规则形成的ID
     */
    @Override
    public String createYiyaID(String type, String chinese) {
        String hashname = "seq_" + type + "_" + DateUtils.dateTime();
        Map<String, Integer> map = redisCache.getCacheMap(hashname);
        boolean hasnonemap = map == null;
        if (hasnonemap) {
            map = new HashMap<String, Integer>();
        }
        String key = "";
        if(type==IYiyaIDService.IDType_LINSHIHAO)
            key +="LS_";
        key += PinyinUtil.toFirstChar(chinese); 
        if(type==IYiyaIDService.IDType_JIEZHANGDAN){
            key+="JZ";   
        }
            
        key += DateUtils.dateTime();
        Integer index = map.getOrDefault(key, 0);
        index += 1;
        map.put(key, index);
        redisCache.setCacheMap(hashname, map);
        if (hasnonemap)
            redisCache.expire(hashname, 48 * 60 * 60);
            
        String   res = key + String.format("%03d", index);
        
        return res;
    }

}
